<?php
/**
 * 重构后的团队页面
 * 使用MVC架构，分离逻辑和视图
 */

session_start();

// 引入必要的文件
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/version_control.php';
require_once __DIR__ . '/includes/team_data.php';
require_once __DIR__ . '/templates/team_template.php';

// 添加防缓存头部
addNoCacheHeaders();

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

try {
    // 初始化数据管理器
    $teamManager = new TeamDataManager($pdo, $user_id);
    
    // 验证用户权限
    $teamManager->validateUserAccess();
    
    // 获取用户信息
    $user = $teamManager->getUserInfo();
    
    // 获取团队数据
    $team_stats = $teamManager->getTeamStats();
    $team_members = $teamManager->getTeamMembers();
    $recent_commissions = $teamManager->getRecentCommissions();
    
    // 生成邀请链接
    $invite_link = $teamManager->getInviteLink($user);
    
    // 准备模板数据
    $template_data = [
        'user' => $user,
        'username' => $username,
        'team_stats' => $team_stats,
        'team_members' => $team_members,
        'recent_commissions' => $recent_commissions,
        'invite_link' => $invite_link
    ];
    
    // 渲染页面
    renderTeamPage($template_data);
    
} catch (Exception $e) {
    // 错误处理
    error_log("团队页面错误: " . $e->getMessage());
    
    // 显示错误页面
    renderErrorPage($e->getMessage());
}

/**
 * 渲染错误页面
 */
function renderErrorPage($error_message) {
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
        <title>错误 - 我的团队</title>
        <?php echo getCssLink('assets/css/mobile.css'); ?>
        <?php echo getCssLink('assets/css/team.css'); ?>
    </head>
    <body>
        <div class="team-container">
            <button class="back-btn" onclick="window.history.back()">← 返回</button>
            
            <div class="team-header">
                <h1>系统错误</h1>
                <p>抱歉，页面加载时出现错误</p>
            </div>
            
            <div class="error-message">
                <h3>错误信息：</h3>
                <p><?php echo htmlspecialchars($error_message); ?></p>
                <p>请稍后重试，或联系管理员。</p>
            </div>
            
            <div style="text-align: center; margin-top: 30px;">
                <button class="qr-btn" onclick="window.location.reload()">重新加载</button>
                <button class="qr-btn secondary" onclick="window.location.href='/'">返回首页</button>
            </div>
        </div>
    </body>
    </html>
    <?php
}
?>
